//// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

import NEChatKit
import NIMSDK
import UIKit
import NECommonKit

@objc
@objcMembers
open class TeamAnnouncementViewModel: NSObject {
    /// 群API单例
    public let teamRepo = TeamRepo.shared
    /// 群信息
    public var currentTeamMember: V2NIMTeamMember?
        
    public var userInTeam: NETeamMemberInfoModel?
    
    
    /// 获取当前用户群信息
    /// - Parameter teamId 群id
    func getCurrentMember(_ teamId: String?, completion: @escaping (V2NIMTeamMember?, NSError?) -> Void) {
        if let tid = teamId {
            let currentUserAccid = IMKitClient.instance.account()

            teamRepo.getTeamMember(tid, .TEAM_TYPE_NORMAL, currentUserAccid) { [weak self] member, error in
                if let currentMember = member {
                    self?.getUserInfo([currentMember]) { error, models in
                        if let users = models {
                            self?.userInTeam = users.first
                            self?.currentTeamMember = currentMember
                        }
                        completion(currentMember, nil)
                    }
                } else {
                    completion(member, error)
                }
            }
            
        }
    }
    
    /// 根据成员信息获取用户信息
    public func getUserInfo(_ members: [V2NIMTeamMember], _ completion: @escaping (NSError?, [NETeamMemberInfoModel]?) -> Void) {
        var accids = [String]()
        var memberModels = [NETeamMemberInfoModel]()
        for member in members {
            accids.append(member.accountId)
            let model = NETeamMemberInfoModel()
            model.teamMember = member
            memberModels.append(model)
        }
        
        ContactRepo.shared.getUserWithFriend(accountIds: accids) { users, v2Error in
            
            if v2Error != nil {
                completion(nil, memberModels)
            } else {
                var dic = [String: NEUserWithFriend]()
                if let us = users {
                    for user in us {
                        if let accid = user.user?.accountId {
                            dic[accid] = user
                        }
                    }
                    for model in memberModels {
                        if let accid = model.teamMember?.accountId {
                            if let user = dic[accid] {
                                model.nimUser = user
                            }
                        }
                    }
                    completion(nil, memberModels)
                }
            }
        }
    }
    
    /// 获取当前群信息
    /// - Parameter teamId 群id
    public func getCurrentTeamInfo(_ teamId: String?, _ completion: @escaping (V2NIMTeam?, NSError?) -> Void) {
        if let tid = teamId {
            teamRepo.getTeamInfo(tid) { team, error in
                completion(team, error)
            }
//            teamRepo.updateTeamInfoMode(tid, .TEAM_TYPE_NORMAL, .TEAM_UPDATE_INFO_MODE_ALL) { error, team in
//                
//            }
        }
    }
    
    ///  更新群公告
    /// - Parameter  teamId: 群组ID
    /// - Parameter  announcement: 群公告
    /// - Parameter  completion: 完成后的回调
    public func updateTeamAnnouncement(_ teamId: String, _ announcement: String, _ serverExtension: String?,
                                       _ completion: @escaping (NSError?, _ announcement: String?, _ serverExtension: String?) -> Void) {
        var params:[String: Any] = [:]
        if let serverExtension = serverExtension {
            params = NECommonUtil.getDictionaryFromJSONString(serverExtension) as! [String : Any]
        }
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateString = dateFormatter.string(from: Date())
        
        params[keyAnnouncementUser] = [
            "id": IMKitClient.instance.account(),
            "time": dateString,
        ]
        params["lastOpt"] = keyAnnouncementUser
        
        let jsonString = NECommonUtil.getJSONStringFromDictionary(params)
        
        NIMSDK.shared().teamManager.updateTeamAnnouncement(announcement, teamId: teamId) { error in
            if error == nil {
                TeamRepo.shared.updateTeamExtension(teamId, .TEAM_TYPE_NORMAL, jsonString) { error in
                    completion(error as NSError?, announcement, jsonString)
                }
            } else {
                completion(error as NSError?, nil, nil)
            }
        }
    }
}
